import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/entity/_.dart';
import 'package:thinking/service/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:thinking/widget/_.dart';
import 'dart:convert' as convert;
import 'dart:convert';

class DynamicNews extends StatefulWidget {
  @override
  _DynamicNews createState() => _DynamicNews();
}

class _DynamicNews extends State<DynamicNews> {
  // 内容Controller
  TextEditingController introduce = TextEditingController();
  TextEditingController tagSearch = TextEditingController();
  List<ImagePickerEntity> imgList = [];
  List<String> imageUrl = [];
  List<Tag> tagSearchList = [] ;
  bool isLoading = false;
  bool isSearch  = false;
  List<dynamic> tagList = [];

  @override
  void initState() {
    super.initState();
    if (SPreferences().getString('dynamic_draft') != '') {
      var obj = jsonDecode(SPreferences().getString('dynamic_draft'));
      imgList = obj["draft_ImgList"].length != 0
          ? obj["draft_ImgList"]
              .map((e) => ImagePickerEntity.fromJson(e))
              .toList()
          : [];
      imageUrl = obj['draft_ImgUrl'].length != 0 ? obj["draft_ImgUrl"] : [];
      introduce.text =
          obj['draft_Introduce'].length != 0 ? obj["draft_Introduce"] : '';
      tagList = obj['draft_TagList']!=null?obj['draft_TagList']
          .toList():[];
      setState(() {});
    }
  }

  @override
  void dispose() {
    introduce.dispose();
    super.dispose();
  }

  Future<void> dynamicPush() async {
    if(introduce.text ==''){
      BotToast.showText(text: '请输入内容!');
      return;
    }
    await DynamicService.dynamicNew(params: {
      "user_id":SPreferences().getInt('user_Id'),
      "dynamic_Introduce":introduce.text,
      "dynamic_ImgList":imageUrl,
      "dynamic_TagList":tagList
    });
    SPreferences().deleteData("dynamic_draft");
    BotToast.showText(text: '发布成功');
    Modular.to.pop();
  }

  getImage(List<ImagePickerEntity> pickedFiles) async {
    setState(() {
      imgList =
          imgList.length == 0 ? pickedFiles : [...imgList, ...pickedFiles];
    });
    toolUploadFile(pickedFiles);
  }

  delImage(int index) {
    setState(() {
      imgList.removeAt(index);
      imageUrl.removeAt(index);
    });
  }

  toolUploadFile(List<ImagePickerEntity> pickedFiles) async {
    List<MultipartFile> filesList = [];
    await Stream<MultipartFile>.fromFutures(pickedFiles
            .map((e) => MultipartFile.fromFile(e.filePath!,
                filename: e.filePath!.substring(
                    e.filePath!.lastIndexOf("/") + 1, e.filePath!.length)))
            .toList())
        .forEach((e) {
      filesList.add(e);
    });
    FormData formData = FormData.fromMap({'files': filesList});
    List<ToolUpLoadFileData> res =
        await PublicService.upLoadFile(params: formData);
    res.forEach((e) {
      imageUrl.add(e.imgUrl!);
    });
  }

  Widget imgView(int e) {
    return Stack(
      children: [
        GestureDetector(
          child: Container(
            height: Screen.setWidth(100),
            width: Screen.setWidth(100),
            decoration: new BoxDecoration(
              borderRadius: new BorderRadius.circular((2.0)),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: Image.file(
                imgList[e].file!,
                fit: BoxFit.cover,
                height: Screen.setWidth(100),
                width: Screen.setWidth(100),
              ),
            ),
          ),
          onTap: () {
            ImagePickers.previewImagesByMedia(
                imgList.map((e) => e.fileMedia!).toList(), e);
          },
        ),
        Positioned(
          right: 0,
          child: GestureDetector(
            onTap: () {
              delImage(e);
            },
            child: Container(
              decoration: BoxDecoration(
                  color: ColorConfig.TextColor,
                  borderRadius:
                      BorderRadius.only(topRight: Radius.circular(10))),
              padding: EdgeInsets.all(2),
              child: Icon(
                Icons.close,
                color: ColorConfig.WhiteBackColor,
                size: 16,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Future<bool> getBack() async {
    var simpleCallBack = await showDialog(
      context: context,
      builder: (context) {
        return SimpleDialog(
          title: Text('提示'),
          children: <Widget>[
            Container(
              height: 80,
              alignment: Alignment.center,
              child: Text('是否保存在草稿箱?'),
            ),
            Divider(
              height: 1,
            ),
            TextButton(
              child: Text('确认',style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16,fontWeight: FontWeight.bold),),
              onPressed: () {
                Navigator.of(context).pop('ok');
              },
            ),
            Divider(
              height: 1,
            ),
            TextButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop('cancel');
              },
            ),
          ],
        );
      },
    );
    if (simpleCallBack == 'ok') {
      await SPreferences().setString(
          'dynamic_draft',
          convert.jsonEncode({
            "draft_Introduce": introduce.text,
            "draft_ImgUrl": [],
            "draft_ImgList": [],
            "draft_TagList":tagList
          }));
      return true;
    } else {
      SPreferences().deleteData("dynamic_draft");
      return true;
    }
  }

  void setTag(String value) {
    int index = tagList.indexOf(value);

    setState(() {
      if (index != -1) {
        tagList.remove(value);
        BotToast.showText(text: '已取消');
        return;
      }
      if(tagList.length>=5){
        BotToast.showText(text: '最多只能添加5个话题哦~');
        return;
      }
      tagList = [value, ...tagList];
      BotToast.showText(text: '添加成功');
    });

  }

  Future<void> showModalBottom(){

    return showModalBottomSheet(
        context: context,
        elevation: 10,
        backgroundColor: ColorConfig.WhiteBackColor,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        builder: (BuildContext context) {


          return StatefulBuilder(builder: (BuildContext context, StateSetter state) {

            Future<void> getTagList(String searchValue) async{
              var res =  (await DynamicService.searchTag(params: {
                "search_Content":searchValue
              }))!;
              state(() {
                tagSearchList = res;
                isLoading = false;
                isSearch = true;
              });
            }

            return GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: (){
                FocusScope.of(context).requestFocus(FocusNode());

              },
              child: Container(
                padding: EdgeInsets.only(top: Screen.setHeight(20)),
                constraints: BoxConstraints(
                    minHeight: Screen.setWidth(400)
                ),
                child: ListView(
                    shrinkWrap: true,
                    children: [
                      Panel(
                        top: 0,
                        bottom: 10,
                        child:  Container(
                          alignment: Alignment.centerLeft,
                          height: Screen.setHeight(50),
                          decoration: BoxDecoration(
                            color: ColorConfig.LineColor,
                            borderRadius: BorderRadius.all(Radius.circular(28.0)),
                          ),
                          child: TextField(
                            cursorWidth: 2,
                            cursorRadius: Radius.circular(10),
                            cursorColor: Colors.red,
                            controller: tagSearch,
                            textInputAction: TextInputAction.search,
                            onSubmitted: (res) async {
                              if (res == '') return;
                              setState(() {
                                isLoading = true;
                              });

                              await getTagList(res);
                            },
                            decoration: InputDecoration(
                              hintText: '添加话题',
                              hintStyle: TextStyle(color: ColorConfig.TextColor),
                              hintMaxLines: 1,
                              prefixIcon: Icon(
                                Icons.add,
                                color: ColorConfig.TextColor,
                                size: 20,
                              ),
                              enabledBorder: UnderlineInputBorder(
                                //选中时下边框颜色
                                borderSide: BorderSide(color: ColorConfig.WhiteBackColor),
                              ),
                              focusedBorder: UnderlineInputBorder(
                                //选中时下边框颜色
                                borderSide: BorderSide(color: ColorConfig.WhiteBackColor),
                              ),
                            ),
                          ),
                        ),
                      ),
                      isLoading?Loading(height: 200,):Empty(child: Column(
                        children: tagSearchList.map((e) =>  Column(
                          children: [
                            Container(
                              height: 50,
                              child: TextButton(
                                style: ButtonStyle(
                                  overlayColor: MaterialStateProperty.all(
                                      ColorConfig.LineColor
                                  ),
                                ),
                                child: Center(
                                  child: Text(
                                    e.tagTitle!,
                                    style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.w600,
                                        color: Colors.black
                                    ),
                                  ),
                                ),
                                onPressed: (){
                                  Modular.to.pop();
                                  setTag(e.tagTitle!);
                                },
                              ),
                            ),
                            Line(height: 1,width: Screen.setWidth(Screen.width(context)-40),),
                          ],
                        )).toList(),
                      ),isShow: tagSearchList.length == 0 && isSearch,),

                    ]

                ),
              ),
            );
          });





        });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          appBar: AppBar(
            backgroundColor: ColorConfig.WhiteBackColor,
            // brightness: Brightness.dark,
            leading: GestureDetector(
              onTap: () async {
                FocusScope.of(context).requestFocus(FocusNode());
                if (introduce.text == '' && tagList.length ==0) {
                  SPreferences().deleteData("dynamic_draft");
                  Navigator.of(context).pop();
                } else {
                  await getBack();
                  Navigator.of(context).pop();
                }
              },
              child: Icon(
                Icons.arrow_back,
                color: ColorConfig.BlackBackColor,
              ),
            ),
            actions: [
              Container(
                width: Screen.setWidth(60),
                padding: EdgeInsets.only(top: 10, bottom: 10),
                margin: EdgeInsets.only(right: 10),
                child: TextButton(
                  style: ButtonStyle(
                      backgroundColor:
                          MaterialStateProperty.all(ColorConfig.ThemeColor),
                      shape: MaterialStateProperty.all(RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(Radius.circular(20)))),
                      elevation: MaterialStateProperty.all(1),
                      overlayColor: MaterialStateProperty.all(
                          ColorConfig.WhiteObsBackColor)),
                  child: Text(
                    '发布',
                    style: TextStyle(color: ColorConfig.WhiteBackColor),
                  ),
                  onPressed: () {
                    dynamicPush();
                  },
                ),
              ),
            ],
          ),
          body: GestureDetector(
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
            },
            child: Container(
              height: Screen.height(context),
              child: Panel(
                top: Screen.setHeight(10),
                child: MediaQuery.removePadding(
                  context: context,
                  removeTop: true,
                  removeBottom: true,
                  child: ListView(
                    shrinkWrap: true,
                    physics: BouncingScrollPhysics(),
                    children: [
                      Container(
                        height: Screen.setHeight(200),
                        child: TextField(
                          maxLines: 8,
                          controller: introduce,
                          decoration: InputDecoration(
                            contentPadding: EdgeInsets.symmetric(
                                horizontal: 8, vertical: 10),
                            filled: true,
                            fillColor: Colors.transparent,
                            enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.transparent),
                            ),
                            hintText: '这一刻的想法',
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.transparent),
                            ),
                          ),
                          style: TextStyle(fontSize: 14),
                          maxLength: 255,
                        ),
                      ),
                      // Align(
                      //   alignment: Alignment.centerRight,
                      //   child: Text(
                      //     "10/255",
                      //     style: TextStyle(fontSize: 14, color: ColorConfig.TextColor),
                      //   ),
                      // ),
                      Container(
                        height: Screen.setHeight(280),
                        child: GridView(
                          shrinkWrap: true,
                          physics: BouncingScrollPhysics(),
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 4,
                            crossAxisSpacing: 4,
                            mainAxisSpacing: 4,
                          ),
                          children: [
                            ...imgList
                                .asMap()
                                .keys
                                .map((e) => imgView(e))
                                .toList(),
                            imgList.length < 9
                                ? ImagePickerWidget(
                              imageListLength: 9 - imgList.length,
                              child: Container(
                                height: Screen.setWidth(100),
                                width: Screen.setWidth(100),
                                decoration: new BoxDecoration(
                                  border: new Border.all(
                                      color: ColorConfig.TextColor,
                                      width: 0.5),
                                  borderRadius:
                                  new BorderRadius.circular((2.0)),
                                ),
                                child: Icon(
                                  Icons.add,
                                  color: ColorConfig.TextColor,
                                ),
                              ),
                              onChange:
                                  (List<ImagePickerEntity> pickedFiles) {
                                getImage(pickedFiles);
                              },
                            )
                                : Container(
                              height: 0,
                              width: 0,
                            )
                          ],
                        )
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          TextButton(
                            style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all(
                                    ColorConfig.LineColor),
                                shape: MaterialStateProperty.all(
                                    RoundedRectangleBorder(
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(16)))),
                                elevation: MaterialStateProperty.all(1),
                                overlayColor: MaterialStateProperty.all(
                                    ColorConfig.WhiteObsBackColor)),
                            onPressed: () {
                              showModalBottom();
                            },
                            child: Text(
                              '#搜索话题',
                              style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.bold,
                                  color: ColorConfig.TextColor),
                            ),
                          ),
                          Wrap(
                            runSpacing: 7,
                            spacing: 7,
                            children: tagList.map((e) => GestureDetector(
                              onTap: (){
                                setTag(e);
                              },
                              child: Text('#'+e,style: TextStyle(fontStyle: FontStyle.italic,color: Colors.lightBlue),),
                            )).toList(),
                          )
                        ],
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
        onWillPop: () async {
          FocusScope.of(context).requestFocus(FocusNode());
          if (introduce.text == '' && tagList.length ==0) {
            SPreferences().deleteData("dynamic_draft");
            return true;
          }
          return await getBack();
        });
  }
}
